<template>
  <div class="app-container">
    <!-- 聊天界面 -->
    <div class="chat-container">
      <!-- 消息展示区域 -->
      <div class="chat-box">
        <div
          v-for="message in messages"
          :key="message.id"
          class="message"
          :class="message.from === 'user' ? 'user-message' : 'ai-message'"
        >
          <!-- <textarea v-model="message.content "></textarea> -->

          <!-- <code>{{ message.content }}</code> -->

          <p v-html=" message.content "></p>
        </div>
      </div>
      <!-- 输入框与发送按钮 -->
      <div class="input-container">
        <el-input
          v-model="userInput"
          placeholder="请输入消息..."
          clearable
          @keyup.enter.native="sendMessage"
          class="chat-input"
        />
        <el-button type="primary" icon="el-icon-send" @click="sendMessage" class="send-button">发送</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
const userInput = ref("");
const messages = ref([]);
const userMsgData = ref({});

const sendMessage = () => {
  if (!userInput.value) return;
  // 添加用户消息
  messages.value.push({
    id: Date.now(),
    content: userInput.value,
    from: "user"
  });

  userMsgData.value.content = userInput.value;
  //   send(this.userMsgData);
  fetchStream();
  // 清空输入框
  userInput.value = "";

  //  currentAiMessageId.value = newAiMessage.id;

  //   // 启动轮询
  //   if (this.isEnd || !this.pollingActive) {
  //     this.isEnd = false;
  //     this.pollingActive = true;
  //     this.polling();
  //   }
};
const fetchStream = async () => {
  const response = await fetch(`/aa/v3/chat`, {
    method: "POST",
    headers: {
      Accept: "text/event-stream",
      "Content-Type": "application/json",
      Authorization:
        "Bearer pat_oBmUIeJLKG7hEqCaNkRTEdZXdgs1vwCmV2YUC54sWKw3c24cOIwrWeezqNq2uZ0g"
    },
    credentials: "include",
    // body: JSON.stringify({
    //   model: "deepseek-r1:7b",
    //   prompt: userInput.value,
    //   stream: false
    // })
    body: JSON.stringify({
      bot_id: "7478533512363180047",
      user_id: "RootUser_2104635204",
      stream: true,
      auto_save_history: true,
      additional_messages: [
        {
          role: "user",
          content: userInput.value,
          content_type: "text"
        }
      ]
    })
  });
  // console.log(response, "response");
  // if (response.ok) {
  //   const reader = response.body.getReader();
  //   // console.log(reader, "reader");
  //   const decoder = new TextDecoder();
  //   let buffer = "";

  //   while (true) {
  //     const { done, value } = await reader.read();
  //     console.log(done, "done");
  //     if (done) break;
  //     let decodeVal = decoder.decode(value, { stream: true });
  //     console.log("decodeVal",decodeVal)
  //     // let rawResponse = JSON.parse(decodeVal).response;
  //     buffer += decodeVal;
  //     console.log(buffer, "buffer");
  //     // 添加 AI 回复占位
  //     const newAiMessage = {
  //       id: Date.now() + 1,
  //       content: buffer,
  //       from: "ai"
  //     };
  //     messages.value.push(newAiMessage);
  //   }
  // }
  if (response.ok) {
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = "";
    const newAiMessage = {
      id: Date.now() + 1,
      content: "", // 初始内容为空
      from: "ai"
    };

    // 将新消息添加到 messages 数组中
    messages.value.push(newAiMessage);

    const updateThreshold = 10;
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      // 解码流数据
      const chunk = decoder.decode(value, { stream: true });
      console.log("chunk", chunk);
      const lines = chunk.split("\n").filter(line => line.trim() !== ""); // 按行分割
      // console.log("lines", lines);
      // buffer += decodeVal;
      for (const line of lines) {
        // console.log("line", line);
        if (line.startsWith("data:")) {
          const data = line.slice(5).trim(); // 移除"data: "前缀
          // console.log("data",data)
          if (data === "[DONE]") continue; // 特殊标记，表示流结束
          try {
            const parsed = JSON.parse(data); // 解析JSON数据
            // console.log("parsed", parsed);

            const content = parsed?.content || ""; // 提取新内容片段
            // const id = parsed?.id || ""; // 提取新内容片段
            // let content1 = JSON.parse(content);
            // console.log("content", content);
            if (
              content &&
              typeof content == "string" &&
              !content.startsWith("{")
            ) {
              const formattedContent = content.replace(/\n/g, "<br>");
              buffer += content;
              // 更新 newAiMessage 的 content
              // newAiMessage.content = buffer;

              // 触发界面更新
              // messages.value = [...messages.value]; // 强制更新 Vue 的响应式数据
              // 大于指定字符，刷新一次
              if (buffer.length >= updateThreshold) {
                // 更新 newAiMessage 的 content
                newAiMessage.content = buffer;

                // 触发界面更新
                messages.value = [...messages.value]; // 强制更新 Vue 的响应式数据
              }
            }
          } catch (error) {
            console.error("Error:", error);
          }
        }

        // 按行分割数据
        // const lines = buffer.split("\n");
        // buffer = lines.pop(); // 剩余未处理的数据放回 buffer
        // let content = "";
        // 处理每一行数据
        // for (const line of lines) {
        //   if (line.startsWith("data:")) {
        //     try {
        //       // 提取 JSON 数据
        //       const jsonData = JSON.parse(line.slice(5).trim());
        //       // console.log("Parsed JSON:", jsonData);
        //       // 如果是消息完成事件，提取内容
        //       // if (jsonData.event === "conversation.message.completed") {
        //       // const content1 = JSON.parse(jsonData.data.content);
        //       console.log("content1", jsonData.content);
        //       //   console.log("Extracted Content:", content);
        //       content += jsonData.content;
        //       // 添加 AI 回复
        //       const newAiMessage = {
        //         id: Date.now() + 1,
        //         content: content, // 提取实际内容
        //         from: "ai"
        //       };
        //       messages.value.push(newAiMessage);
        //       // }
        //     } catch (error) {
        //       console.error("Error parsing JSON:", error);
        //     }
        //   }
        // }
        // const newAiMessage = {
        //   id: Date.now() + 1,
        //   content: content.data, // 提取实际内容
        //   from: "ai"
        // };
        // messages.value.push(newAiMessage);
      }
      newAiMessage.content = buffer;
      messages.value = [...messages.value];
    }
    // const newAiMessage = {
    //   id: Date.now() + 1,
    //   content: buffer, // 提取实际内容
    //   from: "ai"
    // };
    // messages.value.push(newAiMessage);
  }
};
</script>


<style scoped>
.app-container {
  display: flex;
  height: 90vh;
  background-color: #f3f4f6;
  font-family: "Arial", sans-serif;
}

/* 聊天容器 */
.chat-container {
  flex: 1; /* 右侧占比 */
  display: flex;
  flex-direction: column;
  border-left: 1px solid #ddd;
  background-color: #fff;
  overflow: hidden;
}

.chat-box {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #fafafa;
  display: flex;
  flex-direction: column;
}

/* 通用消息样式 */
.message {
  margin: 10px 0;
  padding: 10px;
  max-width: 70%;
  word-wrap: break-word;
  border-radius: 8px;
}

/* 用户消息：右对齐 */
.user-message {
  align-self: flex-end;
  background-color: #e0f7fa;
  text-align: left;
}

/* AI 消息：左对齐 */
.ai-message {
  align-self: flex-start;
  background-color: #f1f1f1;
  text-align: left;
}

/* 输入框和发送按钮 */
.input-container {
  display: flex;
  padding: 10px;
  border-top: 1px solid #e0e0e0;
  background-color: #f9f9f9;
}

.chat-input {
  flex: 1;
  margin-right: 10px;
}

.send-button {
  flex-shrink: 0;
}
</style>



